package com.rocktech.otaserver;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.IPackageInstallObserver;
import android.content.pm.IPackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.lang.reflect.Method;

public class MainActivity extends AppCompatActivity {


    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                try {
                    Intent intent = new Intent();
                    intent.setClassName("com.rocktech.expresscabinet", "com.rocktech.expresscabinet.ui.activity.MainActivity");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();
                } catch (Exception e) {
                    e.printStackTrace();
                    finish();
                }
            }
            return false;
        }
    });

    public static final int INSTALL_REPLACE_EXISTING = 0x00000002;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addListener();
    }

    private void addListener() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                File sdCard = Environment.getExternalStorageDirectory();
                File dir = new File(sdCard, "ota");
                Log.e("btn_install", dir.getPath() + File.separator + "expresscabinet.apk");
                if (Build.VERSION.SDK_INT > 23) {
                    install(dir.getPath() + File.separator + "expresscabinet.apk");
                } else {
                    runInstall(dir.getPath() + File.separator + "expresscabinet.apk");
                }
            }
        }.start();
    }


    private void install(String path) {
        PackageManager mPm = getApplicationContext().getPackageManager();
        Class<?> paramTypes[] = getParamTypes(mPm.getClass(), "installPackage");
        try {
            Method method = mPm.getClass().getMethod("installPackage", paramTypes);
            method.invoke(mPm, Uri.fromFile(new File(path)), null, INSTALL_REPLACE_EXISTING, "com.rocktech.expresscabinet");
            mHandler.sendEmptyMessageDelayed(1, 10000);
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessageDelayed(1, 10000);
        }
    }

    /**
     * 23版本以下的静默安装方法
     *
     * @param path
     */
    private void runInstall(String path) {
        // 静默安装
        IPackageManager mPm;
        try {
            Class<?> forName = Class.forName("android.os.ServiceManager");
            Method method = forName.getMethod("getService", String.class);
            IBinder iBinder = (IBinder) method.invoke(null, "package");
            Log.e("yzy", "iBinder------------:");
            mPm = IPackageManager.Stub.asInterface(iBinder);
            File apkFile = new File(path);
            mPm.installPackage(Uri.fromFile(apkFile), new MyObserver(), INSTALL_REPLACE_EXISTING, apkFile.getPath());
            mHandler.sendEmptyMessageDelayed(1, 10000);
        } catch (Exception e) {
            Log.e("yzy", "Exception:" + e.toString());
            mHandler.sendEmptyMessageDelayed(1, 10000);
        }
    }

    private class MyObserver extends IPackageInstallObserver.Stub {

        @Override
        public void packageInstalled(String packageName, int returnCode)
                throws RemoteException {
            Log.e("yzy", "returnCode:" + returnCode);

        }
    }

    private Class<?>[] getParamTypes(Class<?> cls, String mName) {
        Class<?> cs[] = null;
        Method[] mtd = cls.getMethods();
        for (int i = 0; i < mtd.length; i++) {
            if (!mtd[i].getName().equals(mName)) {
                continue;
            }
            cs = mtd[i].getParameterTypes();
        }
        return cs;
    }


}